<template>
<div class="page-wrapper">
  <Breadcrumb v-bind="breads" />
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <h6 class="card-title">当前角色：</h6>
            <template v-for="(role, index) in roles"> <span :key="index" class="btn btn-outline-info">{{platformText(role.platform)}}-{{role.name}}</span>
            <a :key="role.roleId" href="javascript:void(0);" class="btn-link far fa-trash-alt" v-on:click="subtractRole(index)"></a> </template>
            <div class="col-12">
              <button type="button" class="btn btn-primary" v-on:click="savePlatAdminRoles">保 存</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <form class="form-inline" role="form" @submit.prevent="searchPlatRoles(1)">
              <div class="form-group">
                <label class="control-label">角色名称：</label>
                <div class="btn-group">
                  <input type="text" name="search.role.name" @change="setSearch" class="form-control" style="width:150px;">
                </div>
              </div>
              <div class="form-group">
                <label class="control-label">角色编码：</label>
                <div class="btn-group">
                  <input type="text" name="search.role.code" @change="setSearch" class="form-control" style="width:150px;">
                </div>
              </div>
              <div class="form-group">
                <label class="control-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary">查 找</button>
              </div>
            </form>
          </div>
          <div class="col-12 table-responsive">
            <table class="table table-hover">
              <col width="33%">
              <col width="33%">
              <col width="33%">
              <thead>
                <tr>
                  <th>角色名称</th>
                  <th>角色编码</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(platRole, index) in platRoles" :key="index">
                  <td>{{platRole.role.name}}</td>
                  <td>{{platRole.role.code}}</td>
                  <td>
                    <div class="custom-control custom-checkbox mr-sm-2">
                      <input type="checkbox" class="custom-control-input" :value="platRole.role.roleId" :id="'role' + platRole.role.roleId"
                        v-model="roleIds">
                      <label class="custom-control-label" :for="'role' + platRole.role.roleId">选择</label>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
            <div class="col-12">
              <PageLink v-bind="paging" v-on:go-page="searchPlatRoles($event)" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Footer />
</div>
</template>
<script>
  import $ from 'jquery'
  import cfg from '../dist/js/config'

  import Footer from './ComFooter'
  import Breadcrumb from './ComBreadcrumb'
  import PageLink from './ComPageLink'

  import { platforms } from '../dist/js/enum'

  // 查询条件
  const search = {}

  // 列表数据
  const platRoles = []

  // 分页信息
  const paging = {}

  // 被分配对象
  const platAdmin = {}

  // 已分配的角色
  const roleIds = []
  const roles = []

  function setSearch(event) {
    this.search[event.target.name] = event.target.value
  }
  function platformText(platform) {
    return platforms[platform].text;
  }
  function searchPlatRoles(nowPage) {
    if (nowPage) {
      this.search.nowPage = nowPage
    }
    $.get(cfg.serverPath + '/' + this.platType + 'Role/page/role',
      this.search,
      result => {
        if (result.status != 0) {
          $(document).failMsg(result.message)
          return
        }
        Object.assign(this.paging, this.paging, result.data.paging)
        this.platRoles.splice(0, this.platRoles.length)
        if (!result.data.list) {
          return
        }
        for (let platRole of result.data.list) {
          this.platRoles.push(platRole) }
      })
  }
  function loadPlatAdmin() {
    this.roles.splice(0, this.roles.length)
    this.roleIds.splice(0, this.roleIds.length)
    const search = {
      'id.adminId': this.adminId
    }
    search['id.' + this.platType + 'Id'] = this.platId
    $.get(cfg.serverPath + '/' + this.platType + 'Admin/page/' + this.platType + 'AndAdmin',
      search,
      result => {
        if (result.status != 0) {
          $(document).failMsg(result.message)
          return
        }
        if (!result.data.list) {
          return;
        }
        this.platAdmin = result.data.list[0]
        if (!this.platAdmin.roles) {
          return
        }
        $.get(cfg.serverPath + '/role/page/' + this.platform() + '/!/' + this.platType + '-set-role',
          {
            roleIdIn: this.platAdmin.roles
          },
          result => {
            if (result.status != 0) {
              $(document).failMsg(result.message)
              return
            }
            if (!result.data.list) {
              return
            }
            for (let role of result.data.list) {
              this.roles.push(role)
              this.roleIds.push(role.roleId) }
          })
      })
  }
  function appendRoleByIds() {
    for (let platRole of this.platRoles) {
      for (let roleId of this.roleIds) {
        if (platRole.role.roleId == roleId) {
          let exists = false
          for (let role of this.roles) {
            if (roleId == role.roleId) {
              exists = true
              break
            } }
          if (!exists) {
            this.roles.push(platRole.role);
          }
        } } }
  }
  function subtractRoleByIds() {
    for (let i in this.roles) {
      let role = this.roles[i]
      let exists = false
      for (let roleId of this.roleIds) {
        if (role.roleId == roleId) {
          exists = true
          break
        } }
      if (!exists) {
        this.roles.splice(i, 1)
      }
    }
  }
  function subtractRoleIdByRoles() {
    for (let i in this.roleIds) {
      let roleId = this.roleIds[i]
      let exists = false
      for (let role of this.roles) {
        if (role.roleId == roleId) {
          exists = true
          break
        } }
      if (!exists) {
        this.roleIds.splice(i, 1)
      }
    }
  }
  function subtractRole(index) {
    this.roles.splice(index, 1)
  }
  function savePlatAdminRoles(event) {
    const $target = $(event.target)
    if (!$target.lock()) return

    const platAdmin = {
      id: {
        adminId: this.adminId
      },
      roles: this.roleIds.join(",")
    };

    (platAdmin.id)[this.platType + 'Id'] = this.platId

    $.ajax({
      contentType: 'application/json; charset=UTF-8',
      url: cfg.serverPath + '/' + this.platType + 'Admin/edit',
      type: 'patch',
      data: JSON.stringify(platAdmin),
      success: result => {
        if (result.status != 0) {
          $target.failMsg(result.message)
          return
        }
        $target.infoMsg("保存成功")
      }
    });
  }
  function platform() {
    for (let i in this.platforms) {
      if (this.platforms[i].name.toLowerCase().indexOf(this.platType) != -1) {
        return i
      }
    }
    return 0
  }
  export default {
    props: {
      platType: String,
      platId: String,
      adminId: String
    },
    components: {
      Footer,
      Breadcrumb,
      PageLink
    },
    data() {
      return {
        platforms,
        platAdmin,
        search,
        platRoles,
        paging,
        roleIds,
        roles
      }
    },
    methods: {
      platform,
      setSearch,
      searchPlatRoles,
      loadPlatAdmin,
      platformText,
      appendRoleByIds,
      subtractRoleByIds,
      subtractRoleIdByRoles,
      subtractRole,
      savePlatAdminRoles
    },
    computed: {
      breads() {
        return {
          title: '角色分配：' + '' + (this.platAdmin.admin ? this.platAdmin.admin.name : ''),
          items: [
            {
              href: '#/',
              name: '主页'
            }, {
              href: '',
              name: '账号管理'
            },
            {
              href: '',
              name: '角色分配'
            }
          ]
        }
      }
    },
    created() {
      this.search = {
        nowPage: 1
      }
      this.search[this.platType + '.' + this.platType + 'Id'] = this.platId
      this.searchPlatRoles()
      this.loadPlatAdmin()
    },
    watch: {
      roleIds(newIds, oldIds) {
        if (newIds.length > oldIds.length) {
          this.appendRoleByIds()
        } else {
          this.subtractRoleByIds()
        }
      },
      roles() {
        this.subtractRoleIdByRoles()
      }
    }
  }
</script>
<style scoped>
.btn-outline-info {
	border: 0px;
}

.btn-outline-info:hover {
	color: #2255a4;
	background-color: transparent;
	border-color: #2255a4;
}

.custom-checkbox .custom-control-label::before {
	top: 0.16rem;
}

.custom-checkbox .custom-control-label::after {
	top: 0.16rem;
}

.custom-checkbox .custom-control-label {
	font-weight: 100;
	position: initial;
}
</style>